<template>
  <view class="send-new-container">
    <!-- 顶部导航栏 -->
    <view class="custom-nav-bar" :style="{ height: navBarHeight + 'px' }">
      <!-- 状态栏占位 -->
      <view :style="{ height: statusBarHeight + 'px' }"></view>
      <!-- 导航栏内容 -->
      <view class="nav-content" :style="{ height: navBarContentHeight + 'px' }">
        <!-- 返回按钮 -->
        <view class="nav-left" @click="goBack">
          <text class="nav-back">← 返回</text>
        </view>
        <!-- 标题 -->
        <text class="nav-title">发送新消息</text>
        <!-- 右侧占位 -->
        <view class="nav-right"></view>
      </view>
    </view>

    <!-- 页面内容 -->
    <view class="page-content" :style="{ paddingTop: navBarHeight + 'px' }">
      <!-- 标题输入 -->
      <view class="input-section">
        <text class="input-label">消息标题</text>
        <input class="title-input" v-model="messageTitle" placeholder="请输入消息标题" />
      </view>

      <!-- 工具栏 -->
      <view class="toolbar">
        <view class="tool-row">
          <button class="tool-btn" @click="format('bold')">B</button>
          <button class="tool-btn" @click="format('italic')"><text style="font-style: italic;">I</text></button>
          <button class="tool-btn" @click="format('underline')"><text
              style="text-decoration: underline;">U</text></button>
          <button class="tool-btn" @click="format('strike')"><text
              style="text-decoration: line-through;">S</text></button>
          <button class="tool-btn" @click="format('header', 2)">H2</button>
          <button class="tool-btn" @click="format('header', 3)">H3</button>
          <button class="tool-btn" @click="format('list', 'ordered')">1.</button>
          <button class="tool-btn" @click="format('list', 'bullet')">•</button>
        </view>
        <view class="tool-row">
          <button class="tool-btn" @click="format('align', 'left')">居左</button>
          <button class="tool-btn" @click="format('align', 'center')">居中</button>
          <button class="tool-btn" @click="format('align', 'right')">居右</button>
          <button class="tool-btn" @click="insertDivider">分割线</button>
          <button class="tool-btn" @click="insertImage">图片</button>
          <button class="tool-btn" @click="insertVideo">视频</button>
        </view>
      </view>

      <!-- 富文本编辑器 -->
      <view class="editor-section">
        <editor id="editor" class="rich-editor" placeholder="请输入内容，可插入图片/视频等..." show-img-size show-img-toolbar
          show-img-resize @ready="onEditorReady" />
      </view>

      <!-- 只读预览区：使用 rich-text 渲染完整 HTML，确保视频可见 -->
      <view class="preview-section" v-if="previewHtml">
        <text class="input-label">预览</text>
        <rich-text :nodes="previewHtml"></rich-text>
      </view>

      <!-- 发送按钮区域 -->
      <view class="send-section">
        <button class="send-btn" @click="sendMessage" :disabled="sending">
          发送消息
        </button>
        <text class="char-count">{{ plainTextLength }}/1000</text>
      </view>
    </view>
  </view>
</template>

<script>
  import {
    sendToCom
  } from '../../apis/apis.js'

  export default {
    data() {
      return {
        // 导航栏高度
        statusBarHeight: 0,
        navBarContentHeight: 44,
        navBarHeight: 0,

        // 消息内容
        messageTitle: '',
        editorCtx: null,
        currentHtml: '',
        plainTextLengthInternal: 0,
        mediaCountInternal: 0,
        // 设备号
        deviceNo: "",


        // 发送状态
        sending: false,
        // 当 editorCtx 尚未 ready 时的待插入队列
        pendingHtmlQueue: [],
        // 预览用 HTML（编辑器可能清理 video，这里保持完整）
        previewHtml: ''
      }
    },

    computed: {
      plainTextLength() {
        return this.plainTextLengthInternal
      }
    },

    onLoad() {
      // 计算导航栏高度
      const systemInfo = uni.getSystemInfoSync()
      this.statusBarHeight = systemInfo.statusBarHeight || systemInfo.safeAreaInsets?.top || 20
      this.navBarHeight = this.statusBarHeight + this.navBarContentHeight
    },
    onShow() {
      this.deviceNo = uni.getStorageSync('deviceNo')
      // 启动轻量轮询，实时读取编辑器内容（不监听输入事件）
      if (!this.contentTimer) {
        this.contentTimer = setInterval(() => {
          this.refreshContentLength()
        }, 800)
      }
    },
    onHide() {
      if (this.contentTimer) {
        clearInterval(this.contentTimer)
        this.contentTimer = null
      }
    },
    onUnload() {
      if (this.contentTimer) {
        clearInterval(this.contentTimer)
        this.contentTimer = null
      }
    },

    methods: {
      // 基础地址（与 utils/request.js 一致）
      getHttpBaseUrl() {
        const stored = uni.getStorageSync('baseUrl')
        const origin = stored || '117.23.4.241:8881/api'
        return `http://${origin}`
      },

      // 通用上传（图片/视频），返回可访问 URL
      uploadMedia(filePath, extra = {}) {
        return new Promise((resolve, reject) => {
          const token = uni.getStorageSync('token') || ''
          const url = this.getHttpBaseUrl() + (extra.uploadPath || '/common/upload')
          uni.uploadFile({
            url,
            filePath,
            name: extra.fieldName || 'file',
            header: {
              Authorization: token
            },
            formData: {
              biz: extra.biz || 'news',
              type: extra.type || 'file'
            },
            success: (res) => {
              // console.log('✅ 上传成功 - 原始响应 res:', res)
              // console.log('✅ 上传成功 - res.data 类型:', typeof res.data)
              // console.log('✅ 上传成功 - res.data 内容:', res.data) // 👈 这句最关键！

              try {
                const data = JSON.parse(res.data || '{}')
                // console.log('✅ 解析后的 data:', data) // 👈 看看结构
                const u = data?.data?.url || data?.url || data?.data
                resolve(u)
              } catch (e) {
                console.error('❌ 解析 JSON 失败，原始 res.data:', res.data)
                reject(e)
              }
            },
            fail: (err) => {
              console.error('上传失败详情:', err)
              uni.showToast({
                title: '上传失败: ' + (err.errMsg || err.message),
                icon: 'none'
              })
              reject(err)
            }
          })
        })
      },
      // 返回上一页
      goBack() {
        uni.navigateBack()
      },

      onEditorReady() {
        uni.createSelectorQuery()
          .select('#editor')
          .context((res) => {
            this.editorCtx = res.context
            try {
              console.log('✅ editor ready, flush queue size=', this.pendingHtmlQueue.length)
            } catch (e) {}
            // flush pending html
            if (this.pendingHtmlQueue && this.pendingHtmlQueue.length) {
              const toAppend = this.pendingHtmlQueue.join('')
              this.pendingHtmlQueue = []
              this.appendHtml(toAppend)
            }
            // 同步一次预览内容
            this.getEditorContents().then(c => {
              this.previewHtml = c.html || ''
            })
          })
          .exec()
        // 初始刷新一次字数
        this.refreshContentLength()
      },

      // 基础格式化
      format(name, value) {
        if (!this.editorCtx) return
        try {
          this.editorCtx.format(name, value)
          this.refreshContentLength()
        } catch (e) {
          console.error('format error', e)
        }
      },

      insertDivider() {
        if (!this.editorCtx) return
        try {
          this.editorCtx.insertDivider()
          this.refreshContentLength()
        } catch (e) {
          console.error('insertDivider error', e)
        }
      },

      // 插入图片（先上传，使用远程URL）
      insertImage() {
        if (!this.editorCtx) return
        uni.chooseImage({
          count: 9,
          sizeType: ['compressed'],
          sourceType: ['album', 'camera'],
          success: async (res) => {
            try {
              const paths = res.tempFilePaths || []
              for (const p of paths) {
                const remoteUrl = await this.uploadMedia(p, {
                  type: 'image'
                })
                // await new Promise((r) => {
                this.editorCtx.insertImage({
                  src: remoteUrl,
                  width: '100%',
                })
                // })
              }
              await this.refreshContentLength()
            } catch (e) {
              console.error(' 图片上传/插入失败 - 详细错误:', e)
              console.error(' 错误堆栈:', e.stack) // 打印堆栈
              uni.showToast({
                title: '图片上传失败',
                icon: 'none'
              })
            }
          }
        })
      },

      // 插入视频（上传后生成可被 v-html/rich-text 解析播放的标准结构）
      insertVideo() {
        if (!this.editorCtx) return

        uni.chooseVideo({
          sourceType: ['album', 'camera'],
          compressed: true,
          success: async (res) => {
            try {
              const videoUrl = await this.uploadMedia(res.tempFilePath, {
                type: 'video'
              })
              let posterUrl = ''
              if (res.thumbTempFilePath) {
                try {
                  posterUrl = await this.uploadMedia(res.thumbTempFilePath, {
                    type: 'image'
                  })
                } catch (e) {
                  posterUrl = ''
                }
              }
              // 仅当 poster 为图片类型时才添加 poster；否则省略
              const isImagePoster = posterUrl && /\.(png|jpg|jpeg|webp|gif)$/i.test(posterUrl)
              const posterAttr = isImagePoster ? ` poster="${posterUrl}"` : ''
              // 加上段落包裹，兼容某些端对块级内容的渲染
              const html =
                `<p><br></p><div data-w-e-type="video" data-w-e-is-void>\n<video${posterAttr} controls="true" width="auto" height="auto"><source src="${videoUrl}" type="video/mp4"/></video>\n</div><p><br></p>`
              await this.appendHtml(html)
              await this.refreshContentLength()

            } catch (e) {
              console.error('📹 视频上传/插入失败', e)
              console.error('错误堆栈:', e.stack)
              uni.showToast({
                title: '视频上传失败',
                icon: 'none',
                duration: 3000
              })
            }
          }
        })
      },
      // 追加 HTML 到编辑器内容末尾
      async appendHtml(html) {
        if (!this.editorCtx) {
          // editor 尚未 ready，临时入队
          try {
            console.warn('editor not ready, queue html length=', (html || '').length)
          } catch (e) {}
          this.pendingHtmlQueue.push(html)
          return
        }
        try {
          const cur = await this.getEditorContents()
          const beforeHtml = cur.html || ''
          const merged = beforeHtml + html
          try {
            console.log('📝 append html, beforeLen=', beforeHtml.length, 'addLen=', html.length)
          } catch (e) {}
          await this.setEditorHtml(merged)
          // 更新预览区，确保可见
          this.previewHtml = merged
          this.refreshContentLength()
        } catch (e) {
          console.error('appendHtml error', e)
        }
      },

      getEditorContents() {
        return new Promise((resolve) => {
          if (!this.editorCtx) return resolve({
            html: '',
            delta: {}
          })
          this.editorCtx.getContents({
            success: (res) => resolve(res),
            fail: () => resolve({
              html: '',
              delta: {}
            })
          })
        })
      },

      setEditorHtml(html) {
        return new Promise((resolve) => {
          if (!this.editorCtx) return resolve()
          this.editorCtx.setContents({
            html,
            success: resolve,
            fail: resolve
          })
        })
      },

      async refreshContentLength() {
        const res = await this.getEditorContents()
        const html = (res.html && res.html.length > 0) ? res.html : (this.previewHtml || '')
        const text = html
          .replace(/<[^>]+>/g, '')
          .replace(/&nbsp;/g, ' ')
          .trim()
        this.plainTextLengthInternal = text.length
        try {
          const mediaMatches = html.match(/<(img|video)\b[^>]*>/ig) || []
          this.mediaCountInternal = mediaMatches.length
        } catch (e) {
          this.mediaCountInternal = 0
        }
      },

      // 发送消息
      async sendMessage() {
        if (this.sending) return
        // 点击发送时读取编辑器内容并做非空校验
        await this.refreshContentLength()
        const titleOk = this.messageTitle.trim().length > 0
        const contentOk = this.plainTextLengthInternal > 0 || this.mediaCountInternal > 0
        if (!titleOk || !contentOk) {
          uni.showToast({
            title: '请输入标题和内容',
            icon: 'none'
          })
          return
        }

        this.sending = true

        try {
          const content = await this.getEditorContents()
          let htmlToSend = content.html && content.html.trim().length > 0 ? content.html : this.previewHtml
          if (!htmlToSend) {
            htmlToSend = ''
          }
          // TODO: 这里将来需要添加实际的发送API调用
          const res = await sendToCom({
            equipments: [{
              eqCode: "1",
              remark: ""
            }],
            remark: this.deviceNo,
            type: '消息',
            title: this.messageTitle,
            content: htmlToSend,
            extJson: "",
            status: ""
          })
          console.log('发送消息', {
            title: this.messageTitle,
            html: content.html,
            delta: content.delta
          })

          uni.showToast({
            title: '发送成功',
            icon: 'success',
            duration: 2000
          })

          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        } catch (error) {
          console.error('发送失败:', error)
          uni.showToast({
            title: '发送失败',
            icon: 'error'
          })
        } finally {
          this.sending = false
        }
      }
    }
  }
</script>

<style>
  @import 'sendNewPage.css'
</style>